import { Inject, Provide } from '@midwayjs/decorator';
import { UserService } from './user.service';
import { JwtService } from '@midwayjs/jwt';
import { BaseResponse } from '../utils';
import { encryptWithSalt, makeSalt } from '../utils/salt';

@Provide()
export class AuthService {
  @Inject()
  userService: UserService;

  @Inject()
  jwtService: JwtService;

  async register(requestBody: UserRegisterBodyRequest) {
    const { password, username } = requestBody;
    const user = await this.userService.findUser(username);
    if (user) {
      BaseResponse.error('该用户已经存在');
    }
    // 加密
    const salt = makeSalt();
    const encryptedPassword = encryptWithSalt(password, salt);
    try {
      const result = await this.userService.create({
        username,
        password: encryptedPassword,
        salt,
      });
      return BaseResponse.ok(result.id);
    } catch (error) {
      return BaseResponse.error(error);
    }
  }
  async certificate(entity: { id: string }) {
    const payload = {
      sub: entity.id,
    };
    console.log('payload ==> ', payload);
    try {
      const accessToken = await this.jwtService.sign(payload);
      return BaseResponse.ok(accessToken);
    } catch (error) {
      return BaseResponse.error(error);
    }
  }
  async login(userInfo: UserRegisterBodyRequest) {
    const user = await this.userService.findUser(userInfo.username);
    if (!user) {
      return BaseResponse.error('用户不存在');
    }
    // 明文加密 进行对比
    const encryptedPassword = encryptWithSalt(userInfo.password, user.salt);
    if (encryptedPassword !== user.password) {
      return BaseResponse.error('用户名或密码错误');
    }
    // 返回token
    return this.certificate(user);
  }
}

export interface UserRegisterBodyRequest {
  username: string;
  password: string;
}
